package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.exception.CatchConsumerException;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.utils.common.BCrypt;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.LoginService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;

/**
 * @author szx
 * @date 2022/10/11
 * @description
 */
@Service
public class LoginImpl extends ServiceImpl<WmUserMapper, WmUser> implements LoginService {
    @Override
    public ResponseResult login(WmUserDto dto) {
        if (dto.getName()==null){
            CatchConsumerException.catchException(20001,"姓名不能为空");
        }
        if (dto.getPassword()==null){
            CatchConsumerException.catchException(20002,"密码不能为空");
        }
        WmUser one = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName,dto.getName()));
        if (one==null){
            CatchConsumerException.catchException(20003,"用户不存在");
        }
        if (!BCrypt.checkpw(dto.getPassword(),one.getPassword())){
            CatchConsumerException.catchException(20004,"密码错误");
        }
        if (one.getStatus()!=9){
            CatchConsumerException.catchException(20005,"账号异常");
        }
        one.setLoginTime(new Date());
        upById(one);
        String token = AppJwtUtil.getToken(Long.parseLong(one.getId() + ""));
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("user",one);
        return new ResponseResult().ok(map);
    }
    @Transactional
    public void upById(WmUser wmUser){
        this.updateById(wmUser);
    }
}
